package org.example.software.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.software.entity.DTO.UserUpdate;
import org.example.software.entity.User;
import org.example.software.entity.VO.UserInfo;
import org.example.software.exception.MyException;
import org.example.software.mapper.UserMapper;
import org.example.software.service.UserService;
import org.example.software.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //用户注册
    @Override
    public boolean register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());

        // 检查用户是否已存在
        if (userMapper.selectCount(queryWrapper) > 0) {
            MyException.throwError("该用户已存在", 409);
        }

        // 检查用户账号是否为空
        if (user.getId() == null || user.getId().isEmpty()) {
            MyException.throwError("账号不能为空", 400);
        }

        // 检查用户名是否唯一
        if (user.getName() == null || user.getName().isEmpty()) {
            MyException.throwError("用户名不能为空", 400);
        }

        // 检查用户名是否存在
        if (userMapper.userNameExists(user.getName()) > 0) {
            MyException.throwError("用户名已经存在", 409);
        }

        // 检查密码长度
        if (user.getPassword() == null || user.getPassword().length() < 6 || user.getPassword().length() > 13) {
            MyException.throwError("密码长度必须大于等于6位或小于等于12位", 400);
        }

        // 加密密码并保存
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean success = userMapper.insert(user) > 0;
        return success;
    }

    //用户登录
    @Override
    public String login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        User storedUser = userMapper.selectOne(queryWrapper);

        if (storedUser == null || !passwordEncoder.matches(user.getPassword(), storedUser.getPassword())) {
            MyException.throwError("登录失败，用户不存在或者密码错误", 401);
        }

        // 使用 JWT 生成 Token
        return JwtUtil.generateToken(user.getId(), false);
    }

    //用户个人信息展示
    @Override
    public UserInfo getUserByToken(String token) {
        String userId = JwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            MyException.throwError("用户不存在", 401);
        }

        // 根据用户 ID 查询用户信息
        return userMapper.getUserInfoById(userId);
    }

    //用户个人信息修改
    @Override
    public boolean updateUser(String token, UserUpdate userUpdate) {
        String userId = JwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            MyException.throwError("Token无效或过期", 401);
        }

        // 使用QueryWrapper选择性查询需要的字段
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        // 仅查询用户的必要字段
        User storedUser = userMapper.selectOne(queryWrapper.select("id", "name", "age", "gender", "email"));

        if (storedUser == null) {
            MyException.throwError("用户不存在", 401);
        }

        storedUser.setName(userUpdate.getName());//修改用户名
        storedUser.setAge(userUpdate.getAge()); // 修改年龄
        storedUser.setGender(userUpdate.getGender()); // 修改性别
        storedUser.setEmail(userUpdate.getEmail()); // 修改邮箱

        // 执行更新操作
        return userMapper.updateById(storedUser) > 0;
    }


    //用户密码修改
    @Override
    public boolean changePassword(String token, String oldPassword, String newPassword) {
        // 从 Token 中获取用户 ID
        String userId = JwtUtil.getUserIdFromToken(token);
        if (userId == null) {
            MyException.throwError("Token无效或过期", 401);
        }

        // 根据 userId 查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        // 仅查询用户的必要字段
        User storedUser = userMapper.selectOne(queryWrapper.select("id", "password"));


        if (storedUser == null) {
            MyException.throwError("用户不存在", 401);
        }

        // 校验原密码是否正确
        if (!passwordEncoder.matches(oldPassword, storedUser.getPassword())) {
            MyException.throwError("原密码错误", 400);
        }

        // 校验新密码的有效性
        if (newPassword.length() < 6 || newPassword.length() > 13) {
            MyException.throwError("新密码长度不符合要求", 401);
        }

        // 加密新密码
        storedUser.setPassword(passwordEncoder.encode(newPassword));

        // 更新用户密码
        return userMapper.updateById(storedUser) > 0;
    }


}
